package c2.cross.business.ladder.rank;

import c2.cross.business.CrossBody;
import c2.cross.business.ladder.common.LadderOppoDetail;
import cate.game.pvp.ladder.common.LadderLockOppoQuery;
import cate.game.pvp.ladder.common.LadderLockOppoResult;

import java.util.concurrent.locks.ReentrantLock;

public class LadderLockOppoDo {
    private static final ReentrantLock LOCK = new ReentrantLock();
    public LadderLockOppoResult exe(CrossBody context, LadderRankModule rankMod, LadderLockOppoQuery query) {
        LadderLockOppoResult result = new LadderLockOppoResult();
        LadderOppoDetail oppo = rankMod.getOppoDetail(query.oppoId);
        LadderOppoDetail self = rankMod.getOppoDetail(query.selfId);
        if(oppo == null) {
            return result.fail("排行榜上找不到这个对手了,请刷新后重试+"+query.oppoId);
        }
        if(context.time.now() < oppo.lockUntil) {
            return result.fail("天梯数据发生变化，请稍后重试");
        }
        if(self != null && context.time.now() < self.lockUntil) {
            return result.fail("天梯数据发生变化，请稍后重试");
        }
        LOCK.lock();
        try{
            if(context.time.now() < oppo.lockUntil) {
                return result.fail("天梯数据发生变化，请稍后重试");
            }
            if(self != null && context.time.now() < self.lockUntil) {
                return result.fail("天梯数据发生变化，请稍后重试");
            }
            if(self != null) {
                self.lockUntil = context.time.now() + 900_000;// 15分钟后一定就解锁
            }
            oppo.lockUntil = context.time.now() + 900_000;// 15分钟后一定就解锁
        } finally {
            LOCK.unlock();
        }
        result.success();
        return result;
    }

    public LadderLockOppoResult unLockExe(CrossBody context, LadderRankModule ladderRankModule, LadderLockOppoQuery query) {
        LadderLockOppoResult result = new LadderLockOppoResult();
        LadderOppoDetail oppo = ladderRankModule.getOppoDetail(query.oppoId);
        LadderOppoDetail self = ladderRankModule.getOppoDetail(query.selfId);
        /*if(oppo == null) {
            return result.fail("排行榜上找不到这个对手了,请刷新后重试+"+query.oppoId);
        }*/
        LOCK.lock();
        try {
            if (oppo != null) {
                oppo.lockUntil = context.time.now();
            }
            if (self != null) {
                self.lockUntil = context.time.now();
            }
        } finally {
            LOCK.unlock();
        }

        result.success();
        return result;
    }
}
